package sealte.util.database.conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import sealte.util.xml.XMLReader;

public class DBINFOReader {
	private String configFilePath = null;
	private String connName = null;
	private String driverName = null;
	private String url = null;
	private String user = null;
	private String password = null;

	public DBINFOReader(String configFilePath, String connName) {
		this.configFilePath = configFilePath;
		this.connName = connName;
	}

	public void doInitialize() throws Exception {
		/**
		 * DBINFO.xml -- example:
		 * ------------------------------------------------
		 * <DBINFO> 
		 * <MYSQL>
		 * <DRIVER_NAME>com.mysql.jdbc.Driver</DRIVER_NAME>
		 * <URL>jdbc:mysql://localhost:3306/root_ovms</URL> 
		 * <USER>root</USER>
		 * <PASSWORD>admin</PASSWORD> 
		 * </MYSQL> 
		 * </DBINFO>
		 * ------------------------------------------------
		 */
		this.driverName = XMLReader.getElementText(this.configFilePath, 
				new String[]{this.connName,"DRIVER_NAME"});
		this.url = XMLReader.getElementText(this.configFilePath, 
				new String[]{this.connName,"URL"});
		this.user = XMLReader.getElementText(this.configFilePath, 
				new String[]{this.connName,"USER"});
		this.password = XMLReader.getElementText(this.configFilePath, 
				new String[]{this.connName,"PASSWORD"});
		Class.forName(this.driverName);
	}
	
	public Connection getConnection() throws Exception{
		return DriverManager.getConnection(this.url, this.user, this.password);
	}
	
	public static void close(ResultSet rs,PreparedStatement ps,Connection conn){
		try{
			if(rs!=null){
				rs.close();
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			try{
				if(ps!=null){
					ps.close();
				}
			}catch(SQLException e){
				e.printStackTrace();
			}finally{
				if(conn!=null){
					try{
						conn.close();
					}catch(SQLException e){
						e.printStackTrace();
					}
				}
			}
		}
	}
}
